package com.example.weight.adapter;

import android.content.Context;
import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.ArrayList;
import java.util.List;

public abstract class QuickAdapter<T> extends BaseAdapter {
    private Context mContext;
    protected List<T> mData;

    public QuickAdapter(Context context){
        mContext = context;
    }

    public void swapData(List<T> data) {
        mData = data;
        notifyDataSetChanged();
    }

    public void addData(List<T> data) {
        if (mData == null) {
            mData = new ArrayList<>();
        }
        mData.addAll(data);
        notifyDataSetChanged();
    }

    public List<T> getData() {
        return mData;
    }

    public Context getContext() {
        return mContext;
    }

    @Override
    public int getCount() {
        return mData == null ? 0 : mData.size();
    }

    @Override
    public T getItem(int position) {
        return mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        QuickHolder viewHolder;
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(getConvertViewId(), parent, false);
            viewHolder = new QuickHolder(convertView);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (QuickHolder) convertView.getTag();
        }
        setItemData(viewHolder, mData.get(position), position);
        return convertView;
    }

    public abstract @LayoutRes
    int getConvertViewId();

    public abstract void setItemData(QuickHolder holder, T data, int position);

    public class QuickHolder {
        View mView;

        public QuickHolder(View view) {
            mView = view;
        }

        public T find(@IdRes int id) {
            return (T) mView.findViewById(id);
        }

        public View getView() {
            return mView;
        }
    }
}
